package com.hust.hui.quick.service.dao;

import com.hust.hui.quick.service.domain.UserEntity;
import org.apache.ibatis.annotations.*;

import java.util.Map;

/**
 * Created by yihui on 2017/7/14.
 */
@Mapper
public interface UserMapper {


    @Update("CREATE TABLE `users` (\n" +
            "  `id` int(11) unsigned NOT NULL AUTO_INCREMENT,\n" +
            "  `name` varchar(20) NOT NULL DEFAULT '',\n" +
            "  `email` varchar(40) NOT NULL DEFAULT '',\n" +
            "  `nick` varchar(30) NOT NULL DEFAULT '',\n" +
            "  `password` varchar(64) NOT NULL DEFAULT '',\n" +
            "  `avatar` varchar(255) NOT NULL DEFAULT '',\n" +
            "  `score` int(11) NOT NULL DEFAULT '0' COMMENT '用户的积分，签到发帖使用',\n" +
            "  `isDeleted` tinyint(1) NOT NULL DEFAULT '0',\n" +
            "  `created` int(13) NOT NULL DEFAULT '0',\n" +
            "  `updated` int(13) NOT NULL DEFAULT '0',\n" +
            "  PRIMARY KEY (`id`),\n" +
            "  UNIQUE KEY `name` (`name`),\n" +
            "  UNIQUE KEY `email` (`email`)\n" +
            ") ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;")
    void create();


    @Insert("INSERT INTO users(name,email,nick,password,avatar,score,created,updated) " +
            "VALUES(#{name}, #{email}, #{nick},#{password},#{avatar}, #{score}," +
            "unix_timestamp(now()), unix_timestamp(now()))")
    @Options(useGeneratedKeys = true, keyProperty = "id")
    int insert(UserEntity userEntity);


    @Select("<script>" +
            "select * from users where " +
            "<choose>" +
            "<when test='id!=null'> id=#{id}</when>" +
            "<when test='name!=null'> name=#{name}</when>" +
            "<when test='email!=null'> email=#{email}</when>" +
            "</choose>" +
            "<if test='isDeleted!=null'> and isDeleted=#{isDeleted}</if>" +
            " limit 1" +
            "</script>")
    UserEntity queryOne(Map<String, Object> map);


    @Update("<script>" +
            " UPDATE users " +

            "<set> " +
            "<if test='nick!=null'> nick=#{nick}, </if>" +
            "<if test='password!=null'>password=#{password},</if> " +
            "<if test='avatar!=null'>avatar=#{avatar},</if> " +
            "<if test='score>0'>score=#{score},</if> " +
            " updated=unix_timestamp(now()) " +
            "</set>" +

            "<where> " +
            "<choose>" +
            "<when test='id>0'> id =#{id} </when>" +
            "<when test='name!=null'>name=#{name}></when>" +
            "<when test='email!=null'>email=#{email}></when>" +
            "</choose>" +
            "</where>" +

            "</script>")
    int update(UserEntity userEntity);


    @Delete("DELETE FROM users WHERE id =#{id}")
    void delete(Long id);
}